'use client';

import { useState } from 'react';

interface UserAvatarProps {
  src?: string;
  alt?: string;
  size?: number;
  className?: string;
  fallbackIcon?: React.ReactNode;
  showBorder?: boolean;
}

export default function UserAvatar({
  src,
  alt = '用户头像',
  size = 40,
  className = '',
  fallbackIcon,
  showBorder = true
}: UserAvatarProps) {
  const [imageError, setImageError] = useState(false);

  // 默认的用户图标
  const defaultIcon = fallbackIcon || (
    <svg 
      className="text-slate-400" 
      fill="currentColor" 
      viewBox="0 0 20 20"
      style={{ width: size * 0.5, height: size * 0.5 }}
    >
      <path 
        fillRule="evenodd" 
        d="M10 9a3 3 0 100-6 3 3 0 000 6zm-7 9a7 7 0 1114 0H3z" 
        clipRule="evenodd" 
      />
    </svg>
  );

  // 如果有头像且没有加载错误，显示头像
  if (src && !imageError) {
    return (
      <img
        src={src}
        alt={alt}
        className={`rounded-full object-cover flex-shrink-0 ${showBorder ? 'border-2 border-slate-200' : ''} ${className}`}
        style={{ width: size, height: size }}
        onError={() => setImageError(true)}
      />
    );
  }

  // 否则显示默认图标
  return (
    <div 
      className={`rounded-full bg-slate-100 flex items-center justify-center flex-shrink-0 ${showBorder ? 'border-2 border-slate-200' : ''} ${className}`}
      style={{ width: size, height: size }}
    >
      {defaultIcon}
    </div>
  );
}
